/*
 * @Author: bigflower
 * @Date: 2022-04-13 19:05:37
 * @LastEditors: csh
 * @LastEditTime: 2022-07-28
 * @Description: file content
 * @FilePath: /wochat-vue3-ts-pinia/src/store/chatMessage.ts
 */

import { defineStore, acceptHMRUpdate } from 'pinia';
import msgService from '@/service/chat/messageService';
import { MESSAGE_DIRECTION, MESSAGE_SEND_STATUS } from '@/common/constant';
import { Message } from '@/service/entity/Message';

export const useChatMessageStore = defineStore({
  id: 'chatMessage',
  state: () => ({
    messageMaps: new Map(),
    currentMessages: <Message[]>[], // 指定了这个空数组，是哪种类型的
    isLoaded: false,
  }),
  getters: {},
  actions: {
    loadMessages() {
      this.messageMaps = msgService.loadMessages();
    },
    loadMessage(userId: string) {
      if (!this.isLoaded) {
        this.loadMessages();
        this.isLoaded = true;
      }
      console.log('loadMessage userId', userId);
      this.currentMessages = this.getMessagesWithTime(userId);
      console.log('loadMessage currentMessages', this.currentMessages);
    },
    sendMessage(userId: string, msg: Message) {
      console.log(userId, msg);
      this.currentMessages.push(msg);
      msgService
        .sendMessage(msg)
        .then((res: any) => {
          console.log('send result', res);
          if (res.result === 0) msg.sendStatus = 0;
          else msg.sendStatus = -1;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    resendMessage(msg: Message) {
      msg.sendStatus = MESSAGE_SEND_STATUS.SENDING;
      msgService
        .sendMessage(msg)
        .then((res: any) => {
          console.log('send result', res);
          if (res.result === 0) msg.sendStatus = MESSAGE_SEND_STATUS.SUCCESS;
          else msg.sendStatus = MESSAGE_SEND_STATUS.FAILED;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    getMessagesWithTime(userId: string): Array<Message> {
      console.log('getMessagesWithTime', this.messageMaps, userId);
      const messages = this.messageMaps.get(userId);
      if (messages.length === 0) return [];
      const timeMessages = [];
      timeMessages.push({
        id: messages[0].id + 'middle',
        time: messages[0].time,
        direction: MESSAGE_DIRECTION.MIDDLE_TIME,
      });
      timeMessages.push(messages[0]);
      for (let index = 1; index < messages.length; index++) {
        const date0 = new Date(messages[index - 1].time);
        const date1 = new Date(messages[index].time);
        const differentTime = date1.getTime() - date0.getTime();
        console.log('0000--------------', differentTime);
        if (differentTime > 60 * 1000) {
          timeMessages.push({
            id: messages[index].id + 'middle',
            time: messages[index].time,
            direction: MESSAGE_DIRECTION.MIDDLE_TIME,
          });
          console.log('middle--------------', messages[index].time);
        }
        timeMessages.push(messages[index]);
        console.log('message--------------', messages[index].time);
      }
      console.log('============', timeMessages);
      return timeMessages;
    },
  },
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useChatMessageStore, import.meta.hot));
}
